package com.dindang.ddm.mvp.presenter;

import android.app.Application;
import android.content.Intent;
import android.view.View;

import com.alibaba.android.arouter.core.LogisticsCenter;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.launcher.ARouter;
import com.dindang.ddm.mvp.model.entity.Message;
import com.dindang.ddm.mvp.ui.adapter.multitype.MessageViewBinder;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import in.srain.cube.views.ptr2.PtrDefaultHandler2;
import in.srain.cube.views.ptr2.PtrFrameLayout;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;

import javax.inject.Inject;

import com.dindang.ddm.mvp.contract.MessageContract;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.longxi.gamer_base.dialog.WaitDialog;
import com.longxi.gamer_base.model.LoginEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import static com.jess.arms.utils.ArmsUtils.startActivity;


@FragmentScope
public class MessagePresenter extends BasePresenter<MessageContract.Model, MessageContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private boolean isFirst = true;
    private MultiTypeAdapter mAdapter;
    private Items mItems = new Items();
    private Message.MessageParam mParam = new Message.MessageParam();
    private int START=0;//起始页
    private int  LIMIT=10;//页面条数
    private WaitDialog mWaitDialog;


    @Inject
    public MessagePresenter(MessageContract.Model model, MessageContract.View rootView) {
        super(model, rootView);
    }

    public void initView(){
        mRootView.getToolbarTitle().setText("消息");
        initAdapter();
    }

    private void initAdapter() {
        if(mAdapter == null){
            mAdapter = new MultiTypeAdapter();
            /* 注册类型和 View 的对应关系 */
            mAdapter.register(Message.class, new MessageViewBinder(new MessageViewBinder.OnClickListener() {
                @Override
                public void onClick(int position) {
                    Postcard postcard = ARouter.getInstance().build("/checkline/TaskDetailActivity");
                    ARouter.openDebug();
                    LogisticsCenter.completion(postcard);
                    Class<?> destination = postcard.getDestination();
                    Intent intent = new Intent(mAppManager.getCurrentActivity(),destination);
                    mRootView.getFragment().startActivity(intent);

                }
            }));
            mAdapter.setItems(mItems);
            mRootView.getRecyclerview().setAdapter(mAdapter);
        }
    }

    public void initListener() {
        initPtrFrame();
    }

    public void initDate(){
        if(!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        if(isFirst){
            LogUtils.debugInfo("Message页面重新加载");
            isFirst = false;
            getMessage();
        }
    }

    private void initPtrFrame() {
        mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.REFRESH);
        mRootView.getPtrclassicframelayout().disableWhenHorizontalMove(true);
        mRootView.getPtrclassicframelayout().setLastUpdateTimeRelateObject(this);
        mRootView.getPtrclassicframelayout().setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
//                mRootView.getEmptylayout().setEmptyStatus(EmptyLayout.STATUS_LOADING);
                //下拉刷新
                mRootView.getPtrclassicframelayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mParam.page = START;
                        getMessage();
                    }
                },2000);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return super.checkCanDoRefresh(frame, content, header);
            }

            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                return super.checkCanDoLoadMore(frame, content, footer);
            }
        });
    }

    private void getMessage(){
        //假数据
        mItems.clear();
        mItems.add(new Message(0, "张三","丁当小区11幢11单元11层1101", "","户内区域","家电-洗衣机", "00000000000000001", ""));
        mItems.add(new Message(0, "张三","丁当小区11幢11单元11层1101", "张三、李四、王五","户内区域","家电-洗衣机", "00000000000000001", ""));
        mItems.add(new Message(1, "张三","丁当小区11幢11单元11层1101", "","户内区域","家电-洗衣机", "00000000000000001", "张五"));
        mItems.add(new Message(2, "张三","丁当小区11幢11单元11层1101", "","户内区域","家电-洗衣机", "00000000000000001", "张五"));
        mItems.add(new Message(3, "张三","丁当小区11幢11单元11层1101", "","户内区域","家电-洗衣机", "00000000000000001", "张五"));
        mAdapter.notifyDataSetChanged();

        mRootView.getPtrclassicframelayout().refreshComplete();

//真数据
//        mParam.page = START;
//        mParam.rows = LIMIT;
//        mParam.userId = BaseAppConst.accountInfo.getUserId();
//        mModel.queryMessageList(mParam)
//                .subscribeOn(Schedulers.io())
//                .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
//                .doOnSubscribe(disposable -> {
//
//                }).subscribeOn(AndroidSchedulers.mainThread())
//                .observeOn(AndroidSchedulers.mainThread())
//                .doFinally(() -> {
//                    if(mRootView.getPtrclassicframelayout().isRefreshing()){
//                        mRootView.getPtrclassicframelayout().refreshComplete();
//                    }
//                })
//                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
//                .subscribe(new ErrorHandleSubscriber<BaseResponse<List<Message>>>(mErrorHandler) {
//                    @Override
//                    public void onNext(BaseResponse<List<Message>> response) {
//        if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
//            MyApplication.getInstance().gotoLoginActivity();
//        }
//                        if(!response.isSuccess()){
//                            ArmsUtils.makeText(mApplication, response.getStatuMsg());
//                            return;
//                        }
//                        if(mRootView.getPtrclassicframelayout().isRefreshing()){
//                            mRootView.getPtrclassicframelayout().refreshComplete();
//                        }
//                        if(response.getData().size() < LIMIT){
//                            mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.REFRESH);
//                        }else{
//                            mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.BOTH);
//                            mParam.page++;
//                        }
//                        if(mParam.page == START){
//                            mItems.clear();
//                        }
//                        mItems.addAll(response.getData());
//                        if(mItems.size() == 0){
//                            mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_NO_DATA);
//                        }else{
//                            mRootView.getEmptyLayout().hide();
//                        }
//                        mAdapter.notifyDataSetChanged();
//                    }
//                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;

        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginSuccess(LoginEvent loginEvent){
        if(!isFirst) {
            isFirst = true;
            initDate();
        }
    }
}
